﻿using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;

namespace Jacobi.Seesmic.FeedReader.Model.Extensions
{
    /// <summary>
    /// Extension methods for the Wcf Syndication types.
    /// </summary>
    internal static class SyndicationExtensions
    {
        /// <summary>
        /// Finds a <see cref="SyndicationLink"/> with the specified <paramref name="relationType"/>.
        /// </summary>
        /// <param name="links">Extension reference. Must not be null.</param>
        /// <param name="relationType">The name of the relation type of the link.</param>
        /// <returns>Returns null when not found.</returns>
        public static SyndicationLink FindByRelationType(this IEnumerable<SyndicationLink> links, string relationType)
        {
            var result = from link in links
                         where link.RelationshipType == relationType
                         select link;

            return result.FirstOrDefault();
        }

        /// <summary>
        /// Finds the 'alternate' or 'self' <see cref="SyndicationLink"/>.
        /// </summary>
        /// <param name="links">Extension reference. Must not be null.</param>
        /// <returns>Returns null when not found.</returns>
        public static SyndicationLink FindAlternateOrSelf(this IEnumerable<SyndicationLink> links)
        {
            var link = links.FindByRelationType("alternate");

            if (link == null)
            {
                link = links.FindByRelationType("self");
            }

            return link;
        }

        /// <summary>
        /// Finds an image-link that contains the word 'avatar'.
        /// </summary>
        /// <param name="links">Must not be null.</param>
        /// <returns>Returns null when not found.</returns>
        public static SyndicationLink FindAvatarLink(this IEnumerable<SyndicationLink> links)
        {
            var result = from link in links
                         where link.MediaType == "image"
                         where link.Uri.AbsoluteUri.ToUpperInvariant().Contains("AVATAR")
                         select link;

            return result.FirstOrDefault();
        }

        //public static Uri GetShortcutIconUri(this SyndicationFeed feed)
        //{
        //    var link = feed.Links.FindAlternateOrSelf();

        //    if (link != null)
        //    {
        //        var builder = new UriBuilder(link.GetAbsoluteUri());
        //        builder.Path = "favicon.ico";

        //        return builder.Uri;
        //    }

        //    return null;
        //}
    }
}